package com.tao.pictrue.controller;

import com.alibaba.fastjson.JSONArray;
import com.tao.pictrue.bean.Person;
import com.tao.pictrue.bean.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.List;

@RestController
public class PictureController {

    @Autowired
    private File file;

    @Autowired
    private List<Person> defaultPeople;

    @GetMapping("pic/{count}")
    public Result<List<Person>> getPicture(@PathVariable int count) throws Exception {

        if (file.exists()) {
            // 从文本中读取
            String content = readToString(file);
            if (StringUtils.hasLength(content)) {
                List<Person> people = jsonToPerson(content);
                if (people == null || people.isEmpty()) {
                    return new Result<>(0, "请在jar同级目录创建正确的json数据",
                            count == 1 ? defaultPeople.subList(0, 1) : defaultPeople);
                } else {
                    return new Result<>(0, "读取成功", count == 1 ? people.subList(0, 1) : people);
                }
            } else {
                return new Result<>(0, "请在jar同级目录创建正确的json数据",
                        count == 1 ? defaultPeople.subList(0, 1) : defaultPeople);
            }
        } else {
            // 自己创建
            return new Result<>(0, "请在jar同级目录创建正确的json数据",
                    count == 1 ? defaultPeople.subList(0, 1) : defaultPeople);
        }
    }

    public List<Person> jsonToPerson(String content) {
        try {
            return JSONArray.parseArray(content, Person.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String readToString(File file) {
        String encoding = "UTF-8";
        long length = file.length();
        byte[] content = new byte[(int) length];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(content);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(content, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
